/*
 * TCSS 422 - Spring quarter 2011
 * Team: 	Googlers
 * Members: Deepa Sahni, Krisnil Gounder, Michael Schweiger
 * Date: 	April 8, 2011
 */
package main;

import java.net.MalformedURLException;
import java.net.URL;

import ui.ConsoleReporter;
import ui.Reporter;
import web.PageParser;
import web.PageRetriever;
import buffers.Buffer;
import buffers.PageBuffer;
import buffers.URLBuffer;

public class Main {

	/**
	 * The URL of the "seed" website.
	 */
	public static final String SEED_URL = "http://www.google.com";
	
	/**
	 * The max number of pages that this webcrawler will look for.
	 */
	public static final int MAX_PAGES = 50;
	
	/**
	 * The max amount of milliseconds that this program will sit idle if not pages are
	 * in the buffer.
	 */
	public static final long MAX_IDLE_TIME = 10000;
	
	/**
	 * The reporter object (console or GUI) that this application will use.
	 */
	private final Reporter my_reporter;
	
	/**
	 * The URLBuffer that will be used to synchronize PageRetriever and PageParser threads.
	 */
	private final Buffer<URL> my_url_buffer = URLBuffer.getInstance();
	
	/**
	 * The PageBuffer that will be used to synchronize PageRetriever and PageParser
	 * threads.
	 */
	private final Buffer<String> my_page_buffer = PageBuffer.getInstance();
	
	/**
	 * Facilitates the main loop that initiates all threads and keeps the program moving.
	 * @param the_args The system args, currently ignored.
	 */
	public static void main(String[] args) {
		URL seed = null;
		try {
			seed = new URL(SEED_URL);
		} catch (final MalformedURLException e) {
			System.err.println("SEED URL is invalid, program cannot start!\nTerminating.");
			System.exit(0);
		}
		if (seed == null) {
			throw new IllegalStateException("SEED url did not retrieve properly!");
		}
		Reporter reporter = new ConsoleReporter();
		
		new Main(seed, reporter).start();
	}
	
	/**
	 * Constructor that takes the already checked and established seed URL.
	 * @param url The seed url.
	 */
	private Main(final URL url, final Reporter the_reporter) {
		my_url_buffer.add(url);
		my_reporter = the_reporter;
	}
		
	/**
	 * Starts the application loop.
	 */
	public void start() {

		long time_of_last_page_retrieval = System.currentTimeMillis();
		long idle_time = 0;
		
		while (((URLBuffer) my_url_buffer).getSeenCount() < MAX_PAGES &&
				idle_time < MAX_IDLE_TIME) {
			long current_time = System.currentTimeMillis();
			idle_time += current_time - time_of_last_page_retrieval;
			time_of_last_page_retrieval = current_time;
			if (!my_url_buffer.isEmpty()) {
				idle_time = 0;
				URL temp = my_url_buffer.remove();
				new Thread(new PageRetriever(temp)).start();
			}
			if (!my_page_buffer.isEmpty()) {
				idle_time = 0;
				String temp = my_page_buffer.remove();
				new Thread(new PageParser(temp, my_reporter, null)).start();
			}
		}
	}
}
